'''
Created on Sep 6, 2011

@author: david
'''
import logging
from app.G6.model import Blog, Article

class BlogException(Exception):
    "Package Exceptions"
    def __init__(self,str):
        Exception.__init__(self,str)

class BlogAgent(object):
    """
    Manage business of blogging
    """    

    DEF_ARTICLES = 5

    def get(self,acct,name):
        """
        Return blog by name
        """
        qry = Blog.all().ancestor(acct)
        if name != "Default":
            qry.filter("name =",name)

        return qry.get()
    
    def fetchBlogs(self,acct):
        """
        Fetch list of blogs for acct
        """
        blist = []
        try:
            qry = Blog.all().ancestor(acct)
            for blog in qry:
                blist.append(blog)
        except:
            # uh oh
            logging.exception("!! Error fetching Blog list for %s" % acct.uid)
            blist = None
            
        return blist
            
    def fetchArticles(self, blog, start=0, count=DEF_ARTICLES):
        """
        Gather all most recent artilces from blog
        """
        alist = []
        logging.debug("~~ blog: %s" % blog)
        
        try:
            qry = Article.all().ancestor(blog).order("-tmstmp")
            
            for article in qry.fetch(count, offset=start):
                alist.append(article) 
        except:
            # uh oh
            logging.exception("!! Error Articles for %s" % blog.name)
            alist = None
            
        
        return alist
    
    def postArticle(self,blog,subj, txt, tags):
        """
        Post new article for Blog
        """
        rv = None
        try:
            a = Article(parent= blog)
            a.subj = subj
            a.text = txt
            a.tags = tags
            a.aid = "%s-A%s" % (blog.bid,Article.all().ancestor(blog).count())
            a.put()
            rv = a
        except:
            # uh oh
            logging.exception("!! Error adding article to %s" % blog.name)
            rv = None
            
        return rv
    
    def createBlog(self, acct, name, description, tags, default=False):
        """
        Create new blog and associate w/ account
        """
        try:
            # create blog recored
            blog = Blog(parent=acct, name=name, description=description,tags=tags)
            
            # build id
            blog.bid = "%s-B%s" % (acct.aid,Blog.all().ancestor(acct).count()) 
            
            blog.put()
            
            # check for default flag
            if default:
                self.setDefault(acct, blog)
                                
            # commit it
            logging.info("++ Created new Blog %s for %s" % (name, acct.uid))

        except:
            # uh oh
            logging.exception("!! Error building new Blog")
            blog = None
            
        # return
        return blog
    
    def getDefault(self, acct):
        """
        get default blog for account
        """
        rv = None
        blogs = self.fetchBlogs(acct)
        for blog in blogs:
            if blog.default:
                rv = blog
    
        # if none set, send first blog            
        if not rv: rv = blogs[0]
        
        return rv
    
    def setDefault(self, acct, blog):
        """
        Set default blog for account
        """
        for b in Blog.all().ancestor(acct).fetch(100):
            # set default
            blog.default = b.key == blog.key
            blog.put()
        
        return blog
    